package com.zut.oss.adapter;

import com.zut.oss.entity.FileInfo;
import com.zut.oss.adapter.StorageAdapter;
import com.zut.oss.util.MinioUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Service("minioServiceimpl")
public class MinioOssAdapterImpl implements StorageAdapter {


    //调用通用的Minio内的方法来实现
    @Resource
    private MinioUtil minioUtil;

    /**
     * Minio的url
     */
    @Value("${minio.url}")
    private String url;

    //创建桶
    @Override
    public void createBucket(String bucket) throws Exception {
        minioUtil.createBucket(bucket);
    }

    //上传文件
    @Override
    @SneakyThrows
    //接收文件通常使用MultipartFile类
    public void uploadBucket(MultipartFile multipartFile, String bucket, String ObjectName) {
        minioUtil.createBucket(bucket);
        if (ObjectName!=null)
            //上传文件时需要传入文件的输入流
        minioUtil.uploadBucket(multipartFile.getInputStream(),bucket,ObjectName+"/"+multipartFile.getName());
        else
            minioUtil.uploadBucket(multipartFile.getInputStream(),bucket,multipartFile.getName());


    }

    //获得所有桶名字
    @Override
    @SneakyThrows
    public List<String> getAllBucket() {
        return minioUtil.getAllBucket();
    }

    //获得桶内所有文件名字
    @Override
    @SneakyThrows
    public List<FileInfo> getBucketAllFileName(String bucket) {
        return minioUtil.getBucketAllFileName(bucket);
    }

    //下载文件
    @Override
    @SneakyThrows
    public InputStream downLoad(String bucket, String objectName) {
        return minioUtil.downLoad(bucket, objectName);
    }

    //删除桶
    @Override
    @SneakyThrows
    public void deleteBucket(String bucket) {
        minioUtil.deleteBucket(bucket);

    }

    //删除桶内文件
    @Override
    @SneakyThrows
    public void deleteBucketFile(String bucket, String objectName) {

        minioUtil.deleteBucketFile(bucket,objectName);
    }

    //获取文件Url
    @Override
    @SneakyThrows
    public String getUrl(String bucket, String objectName) {
        return url+"/"+bucket+"/"+objectName;
    }

}
